﻿Imports System
Imports System.Runtime.InteropServices
Imports System.Threading

Namespace System.Workflow.Runtime.DebugEngine
    Friend NotInheritable Class ProgramPublisher
        ' Methods
        Public Function Publish(ByVal controller As DebugController) As Boolean
            If Me.isPublished Then
                Return False
            End If
            Try 
                Me.controller = controller
                Dim thread As New Thread(New ThreadStart(AddressOf Me.PublisherThreadFunc))
                thread.SetApartmentState(ApartmentState.MTA)
                thread.IsBackground = True
                thread.Start
                thread.Join
            Catch exception1 As Exception
            End Try
            Return Me.isPublished
        End Function

        Private Sub PublisherThreadFunc()
            Try 
                Me.publisher = [TryCast](New WDEProgramPublisher,IWDEProgramPublisher)
                Me.wdeProgramNodeSingleton = New ProgramNode(Me.controller)
                Me.gchWdeProgramNode = GCHandle.Alloc(Me.wdeProgramNodeSingleton)
                Me.publisher.Publish(Me.wdeProgramNodeSingleton)
                Me.isPublished = True
            Catch exception1 As Exception
            End Try
        End Sub

        Public Sub Unpublish()
            If Me.isPublished Then
                Try 
                    Dim thread As New Thread(New ThreadStart(AddressOf Me.UnpublishThreadFunc))
                    thread.SetApartmentState(ApartmentState.MTA)
                    thread.IsBackground = True
                    thread.Start
                    thread.Join
                Catch exception1 As Exception
                End Try
            End If
        End Sub

        Private Sub UnpublishThreadFunc()
            Try 
                Me.publisher.Unpublish(Me.wdeProgramNodeSingleton)
            Catch exception1 As Exception
            Finally
                Me.gchWdeProgramNode.Free
                Marshal.ReleaseComObject(Me.publisher)
                Me.publisher = Nothing
            End Try
            Me.isPublished = False
        End Sub


        ' Fields
        Private controller As DebugController
        Private gchWdeProgramNode As GCHandle
        Private isPublished As Boolean
        Private publisher As IWDEProgramPublisher = Nothing
        Private wdeProgramNodeSingleton As IWDEProgramNode
    End Class
End Namespace

